package com.cws.backup.factory.impl;

import cn.hutool.core.date.DateUtil;
import com.cws.backup.common.CommandUtil;
import com.cws.backup.constant.Command;
import com.cws.backup.entity.BackupEntity;
import com.cws.backup.factory.BackupHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;

/**
 * @author cws
 */
@Slf4j
public class MysqlBackupHandler implements BackupHandler {

    @Override
    public void backup(BackupEntity backupEntity) {
        log.info("开始执行{}备份...", backupEntity.toString());
        File dir = new File(backupEntity.getLocation());
        if (!dir.exists()) {
            log.info("目录不存在，创建目录...");
            dir.mkdirs();
        }

        String file = backupEntity.getLocation() + File.separator + DateUtil.format(new Date(), "yyyyMMdd_HHmmss") + "_" + backupEntity.getDb() + ".sql";
        file = file.replaceAll("\\\\", "\\\\\\\\");
        String command = Command.MYSQL_COMMAND
                .replaceAll("#\\{ip}", backupEntity.getIp())
                .replaceAll("#\\{username}", backupEntity.getUsername())

                .replaceAll("#\\{password}", backupEntity.getPassword())
                .replaceAll("#\\{db}", backupEntity.getDb())
                .replaceAll("#\\{file}", file);


        String[] cmd = new String[3];
        if (CommandUtil.isLinuxSystem()) {
            cmd[0] = "/bin/sh";
            cmd[1] = "-c";
//            如果linux客户端mysql是8.0.30的,mysqldump的版本大于8,而我的要备份的MySQL数据库是比较老的版本(5.7),需要加上下面这行,不然备份就会报错
//            版本一致不需要添加
//            command = command + " --column-statistics=0";
        } else {
            cmd[0] = "cmd";
            cmd[1] = "/c";
        }
        cmd[2] = command;

        log.info(command);
        try {
            Process exec = Runtime.getRuntime().exec(cmd);
            if (exec.waitFor() != 0) {
                InputStream is = exec.getErrorStream();
                if (is != null) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(is, System.getProperty("os.name").startsWith("Win") ? "GBK" : "UTF-8"));
                    String line;
                    StringBuilder sb = new StringBuilder();
                    while ((line = in.readLine()) != null) {
                        sb.append(line);
                    }
                    log.info("备份失败,原因:" + sb);
                    return;
                }
                log.info("备份失败,exec.waitFor=" + exec.waitFor());
                return;
            }
        } catch (Exception e) {
            log.info("备份异常:" + e.getMessage());
            return;
        }
        log.info("备份成功!");
    }
}
